package com.ithiema.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.ithiema.reggie.common.BaseContext;
import com.ithiema.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
 * 检查用户是否已经完成登录   (过滤器)
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
//Filter(过滤器的意思)
  // 注释:+Filter(过滤器的意思)
    //继承: 继承Filter(过滤器的意思)
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //强转格式把ServletRequest转为HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1、获取本次请求的URI
        String requestURI = req.getRequestURI();  //  /backend/index.html
        log.info("拦截到请求{}",requestURI);

        //定义不需要处理的请求路径
        String[] urls = new String[]{"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/**"};

        //2、判断本次请求是否需要处理 ( 抽成方法了 )
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if (check){
            log.info("本次请求{}不需要处理",requestURI);
            chain.doFilter(req,resp);
            return;
        }

        //4、判断登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("employee"));

            // 调用BaseContext的setCurrentId方法将当前登录用户ID存入ThreadLocal。
            //把当前登陆用户设置到本地线程中
            long empld = (long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empld);

            chain.doFilter(req,resp);
            return;
        }
        log.info("用户未登录");


        //判断移动端用户登陆状态，如果已登陆直接放行
        Long userId = (Long) ((HttpServletRequest) request).getSession().getAttribute("user");
        if (userId!=null){
            log.info("用户一登陆，就放行:{}",userId);
            //把当前登陆用户设置到本地线程中
            BaseContext.setCurrentId(userId);
            chain.doFilter(req,resp);
            return;
        }


        //5、如果未登录则返回未登录结果，通过 输出流 方式向客户端页面响应数据
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     * 会被上面调用方法
     * @return
     */
    public boolean check(String[] urls, String requestURI){
        //增强for  遍历 String[] urls 集合
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }


}
